<template funcCode="uap.dashboard.public" autoRoute="true">
  <div class="container">
    <el-splitter>
      <!-- 左侧树形菜单 -->
      <el-splitter-panel size="230px">
        <TreeMenu
          :tree-data="treeMenuData"
          :default-expanded-keys="defaultExpandedKeys"
          :default-selected-key="defaultSelectedKey"
          :config="props.config"
          @selected-node="onNodeSelected"
        />
      </el-splitter-panel>

      <!-- 右侧内容 -->
      <el-splitter-panel>
        <div class="table-wrapper">
          <div class="toolbar-container-left">
            <span v-if="selectedProject" class="toolbar-container-left-text">{{
              selectedProject.label
            }}</span>
          </div>
          <CToolbar
            :fields="fields"
            :search-fields="['name']"
            :visibleButtons="toolbarOptions"
            @search="handleSearch"
          >
            <template #toolbar-right-after>
              <el-button
                style="margin-left: 10px; width: 80px; height: 32px"
                :icon="Delete"
                type="primary"
                @click="handleAddClick('delete')"
              >
                <span class="button-text">删除</span>
              </el-button>
              <div
                v-if="
                  selectedProject && ['0', '9999'].includes(selectedProject.id)
                "
              >
                <el-button
                  style="margin-left: 10px; width: 80px; height: 32px"
                  type="primary"
                  @click="handleAddClick('add')"
                  ><el-icon color="#fff"><plus /></el-icon>
                  <span class="button-text">导入</span>
                </el-button>
                <el-button
                  style="margin-left: 10px; width: 80px; height: 32px"
                  type="primary"
                  @click="handleAddClick('down')"
                  ><el-icon color="#fff"><plus /></el-icon>
                  <span class="button-text">导出</span>
                </el-button>
              </div>
            </template>
          </CToolbar>

          <div class="table-container">
            <!-- 批量操作浮层 -->
            <CLBatchOpToolbar
              :show="showCLBatchOpToolbar"
              :show-delete="false"
              :selected-count="selectedRecords.length"
            >
              <button
                class="batch-btn"
                style="color: #d54941"
                @click="handleBatchDelete"
              >
                删除
              </button>
            </CLBatchOpToolbar>
            <CLTable
              :fields="fields"
              :initial-data="tableData"
              :tableConfig="tableConfig"
              :router-fields="routerFields"
              :more-actions="moreActions"
              @onMoreAction="handleMoreAction"
              @pagerChange="pagerChange"
              @show:records="handleShowRecords"
            />
            <FileUploaderDialog
              ref="fileUploadDialogRef"
              @UploadComplete="UploadComplete"
            />
          </div>
        </div>
      </el-splitter-panel>
    </el-splitter>
  </div>
  <CDialog
    :title="operate === 'create' ? '新建' : '编辑'"
    v-model="dialogVisible"
    @handleDialogOk="handleCreateOrEdit"
    :fields="dialogFields"
    :nodeData="selectedNode"
  ></CDialog>
</template>

<script setup lang="ts">
  import TreeMenu from "@/components/TreeMenu.vue";
  import CLTable from "@/components/CLTable/index.vue";
  import CToolbar from "@/components/CToolbar.vue";
  import { ref, onMounted, reactive, provide, watch } from "vue";
  import { dataReportFields, type ProjectNode } from "@/data/wbsData.ts";
  import { Delete, Plus } from "@element-plus/icons-vue";
  import CLBatchOpToolbar from "@/components/CLBatchOpToolbar.vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import CDialog from "@/components/CDialog.vue";
  import { deepCopy, formatDate } from "@/utils/common.ts";
  import type { CacheData, DynamicField } from "@/data/wbsFields.ts";
  import { useRoute, useRouter } from "vue-router";
  import { mockData } from "@/views/demo/data/data.ts";
  import type { ProjectSearchRequest } from "@/interface/project.ts";
  import {
    bathDownLoadTaskFile,
    createTaskData,
    deleteDataFlowBatch,
    deleteItem,
    editItem,
    getItemsList,
    getTaskSimpleTree,
    uploadFile,
  } from "@/components/wbsDraw/api.ts";
  import FileUploaderDialog from "@/components/wbsDraw/FileUploaderDialog.vue";

  interface dataReport {
    config: Record<any, any>;
  }
  const props = defineProps<dataReport>();
  const treeMenuData = ref<any[]>([]);
  const tableData = ref<ProjectNode[]>([]);

  const fields = ref<DynamicField[]>(dataReportFields);
  const selectedProject = ref();
  const toolbarOptions = ref({
    search: {
      enable: true,
      name: "请输入名称搜索",
    },
  });
  const moreActions = ref([
    { key: "export", label: "导出" },
    { key: "delete", label: "删除" },
  ]);
  const pages = reactive<CacheData>({
    pageNo: 1,
    pageSize: 20,
    total: 10,
    filterConditions: [],
    sortCondition: {
      condition: null,
      direction: "asc",
    },
    lineHeight: "medium",
  });

  const defaultExpandedKeys = ref<(string | number)[]>(["2"]); // 默认展开节点
  const defaultSelectedKey = ref<string | number>("1"); // 默认选中节点
  const showCLBatchOpToolbar = ref(false);
  const selectedRecords = ref<ProjectNode[]>([]);
  const dialogVisible = ref(false);
  const operate = ref("create");
  const selectedNode = ref({});
  const dialogFields = ref<DynamicField[]>(fields.value);
  const router = useRouter();
  const route = useRoute();
  const routerFields = ref(["status", "assignAllTenant"]);
  const currentProjectId =
    (route.params as any).projectId || (route.query as any).projectId || "";
  const fileUploadDialogRef = ref();
  // 模拟异步数据加载
  const fetchData = async () => {
    try {
      pages.filterConditions = [
        {
          field: "projectId",
          operator: "=",
          value: currentProjectId,
        },
      ];
      pages.filterConditions = pages.filterConditions.map((item) => ({
        ...item,
      }));
      let queryParams: ProjectSearchRequest = {
        pageNo: pages.pageNo,
        pageSize: pages.pageSize,
        conditions: pages.filterConditions,
      };
      const response = await getTaskSimpleTree(queryParams);
      console.log(response, "response");
      treeMenuData.value = [
        {
          id: "0",
          name: { zh_CN: "项目输入" },
        },
        ...response,
        {
          id: "9999",
          name: { zh_CN: "任务输出" },
        },
      ];
      defaultSelectedKey.value = (treeMenuData.value as any[])[0].id;
      selectedProject.value = (treeMenuData.value as any[]).find(
        (item) => item.id === defaultSelectedKey.value,
      );
      onNodeSelected(selectedProject.value);
    } catch (e) {
      ElMessage.error("数据加载失败", e);
    }
  };

  const tableConfig = ref({
    editable: false,
    page: {
      enable: true,
    },
    tableH: "calc(100vh -90px)",
    borderMode: "none",
    tree: { enabled: false },
    enableCustomDrag: false,
    OperationsColumnMode: "text", // 操作列模式，text为文本模式
    OperationsColumnWidth: 100, //自定义操作列宽度
    rowSeriesNumber: {},
    frozenColCount: 2,
    rightFrozenColCount: 1, // 冻结后面列数
  });

  // 选中树节点事件
  const onNodeSelected = async (node: ProjectNode) => {
    selectedProject.value = node;
    try {
      let conditions = [
        {
          field: "projectId",
          operator: "=",
          value: currentProjectId,
        },
      ];
      if (node.id === "0") {
        conditions.push({
          field: "type",
          operator: "=",
          value: "PROJECT_INPUT",
        });
      } else if (node.id === "9999") {
        conditions.push({
          field: "type",
          operator: "=",
          value: "PROJECT_OUTPUT",
        });
      } else {
        conditions.push({
          field: "taskId",
          operator: "=",
          value: node.id,
        });
      }
      const params = {
        conditions: conditions,
        pageNo: 1,
        pageSize: 9999,
      };
      let response = await getItemsList(params);
      console.log(response.result, "response");
      if (response.result.length > 0) tableData.value = response.result;
      else tableData.value = [];
    } catch (e) {}
    //然后根据该节点来查找其下面的任务项，在重新加载数据
  };

  // 处理搜索事件
  const handleSearch = (keyword: string, searchFields?: string[]) => {
    console.log("搜索关键词:", keyword);
    console.log("搜索字段:", searchFields);
    // 实际项目中，这里可以调用API搜索数据
    // 例如: await axios.get('/api/wbs/search', { params: { keyword, searchFields } });

    // 前端搜索实现 - 过滤表格数据
    if (!keyword.trim()) {
      // 如果关键词为空，恢复原始数据
      //这里应该重新根据选择的节点来重新加载数据
      tableData.value = JSON.parse(JSON.stringify(mockData));
      return;
    }

    // 搜索实现，根据ProjectNode结构搜索相关字段
    const filteredData = JSON.parse(JSON.stringify(mockData));

    // 默认搜索字段
    const defaultSearchFields = ["name", "assignee", "status"];
    // 使用传入的搜索字段或默认字段
    const fieldsToSearch = searchFields?.length
      ? searchFields
      : defaultSearchFields;

    const searchInTree = (data: ProjectNode[]): ProjectNode[] => {
      return data.filter((node): boolean => {
        // 搜索当前节点
        let matchesSearch = false;

        // 根据指定的字段进行搜索
        for (const field of fieldsToSearch) {
          if (
            node[field as keyof ProjectNode] &&
            String(node[field as keyof ProjectNode])
              .toLowerCase()
              .includes(keyword.toLowerCase())
          ) {
            matchesSearch = true;
            break;
          }
        }
        // 如果有子节点，递归搜索
        // if (node.children && node.children.length > 0) {
        //   node.children = searchInTree(node.children);
        //   // 如果当前节点不匹配但子节点有匹配，也保留当前节点
        //   return matchesSearch || (node.children && node.children.length > 0);
        // }
        return matchesSearch;
      });
    };
    tableData.value = searchInTree(filteredData);
  };
  // 更新节点的钩子函数
  const handleUpdateNode = (node: ProjectNode, field: string, value: any) => {
    console.log("更新节点:", node, field, value);

    // 实际项目中，这里应该调用API更新数据
    // 例如: await axios.put('/api/wbs/update', { id: node.id, field, value });

    // 这里仅作前端演示，实际更新逻辑由wbsTable组件内部处理
    // 如果需要在父组件中处理更新逻辑，可以在这里实现
  };

  // 处理更多操作
  const handleMoreAction = async (action: string, node: ProjectNode) => {
    // console.log("handleMoreAction", action, node);
    try {
      switch (action) {
        case "delete":
          // 确认删除
          await ElMessageBox.confirm(
            `确定要删除项目"${node.fileName}"吗？`,
            "删除确认",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
            },
          );
          await handleDeleteNode(node);
          await onNodeSelected(selectedProject.value);
          break;

        case "edit":
          // 编辑项目逻辑
          console.log("导出项目:", node);
          selectedNode.value = deepCopy(node);
          dialogVisible.value = true;
          operate.value = "edit";
          // ElMessage.info("编辑项目功能待实现");
          break;

        case "export":
          // 导出项目逻辑
          await exportFile(node);
          break;

        case "layoutSetting":
          // 布局设置逻辑
          console.log("布局设置:", node);
          // ElMessage.info("布局设置功能待实现");
          router.push("/design");
          break;

        case "switch":
          console.log("点击按钮:", node);
          handleUpdateNode(node.originData.id, node.field, node.originData);
          break;

        default:
          console.warn("未知操作:", action);
      }
    } catch (error) {
      if (error !== "cancel") {
        console.error("操作失败:", error);
        ElMessage.error("操作失败，请重试");
      }
    }
  };
  const tableListQuery = reactive<{
    pageNo: number;
    pageSize: number;
    sortParams: any[];
    conditions: any[];
  }>({
    pageNo: 1,
    pageSize: 10,
    sortParams: [],
    conditions: [],
  });

  const showDeleteMessage = (res: any) => {
    if (res.deleted.length > 0)
      showFileMessage("success", `${res.deleted.length}个文件删除成功`);
    else if (res.failed.length > 0) {
      const message = res.failed.map((failedId: any) => {
        const file = tableData.value.find(
          (item: any) => item.fileId === failedId,
        );
        return file ? `文件名称${file.fileName}` : `未知文件 (ID: ${failedId})`;
      });
      showFileMessage("error", `${res.failed.length}个文件删除失败`, message);
    } else if (res.noPermission.length > 0) {
      const message = res.failed.map((failedId: any) => {
        const file = tableData.value.find(
          (item: any) => item.fileId === failedId,
        );
        return file ? `文件名称${file.fileName}` : `未知文件 (ID: ${failedId})`;
      });
      showFileMessage(
        "warning",
        `${res.noPermission.length}个文件没有删除权限`,
        message,
      );
    }
  };
  const handleExportResponse = (
    response: any,
    filename: string = "export.zip",
  ) => {
    // 创建 Blob 对象
    const blob = new Blob([response], { type: "application/octet-stream" });

    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = filename;

    // 触发下载
    document.body.appendChild(link);
    link.click();

    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  };
  const handleDeleteNode = async (node: ProjectNode) => {
    const res = await deleteItem(node.id);
    showDeleteMessage(res, "删除");
    console.log(res);
  };
  const exportFile = async (node: ProjectNode | ProjectNode[]) => {
    try {
      console.log("导出项目:", node, typeof node);
      const params = Array.isArray(node) ? node : [node];
      const res = await bathDownLoadTaskFile(params);
      // 处理字节流响应
      if (res) {
        handleExportResponse(res, "data-export.zip");
        showFileMessage("success", "导出成功");
      } else showFileMessage("error", "导出失败");
    } catch (error) {
      console.error("导出失败:", error);
      ElMessage.error("导出失败，请重试");
    }
  };

  // 处理添加按钮点击事件
  const handleAddClick = async (type: "delete" | "add" | "down") => {
    // 这里可以根据项目需求实现具体的添加逻辑
    switch (type) {
      case "delete": {
        // 添加子节点
        await ElMessageBox.confirm(`确定要删除全部项目吗？`, "删除确认", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        });
        const params = tableData.value
          .map((item: any) => {
            return item.id;
          })
          .join(",");
        console.log(params);
        const res = await deleteDataFlowBatch(params);
        console.log("res", res);
        showDeleteMessage(res, "删除");
        await onNodeSelected(selectedProject.value);
        break;
      }
      case "add":
        // 添加同级节点
        if (fileUploadDialogRef.value) fileUploadDialogRef.value.visible = true;
        break;
      case "down": {
        await exportFile(tableData.value);
        break;
      }
    }
  };
  const showFileMessage = (
    type: "success" | "warning" | "error",
    title: string,
    details?: string[],
    duration = 10000,
  ) => {
    const colorMap = {
      success: "success",
      warning: "warning",
      error: "error",
    } as const;

    // 拼接 HTML 内容
    const messageHTML = `
    <div style="min-width: 230px;">
      <div>${title}</div>
      ${
        details && details.length
          ? `<span style="font-size: 11px;">${details.join("，")}</span>`
          : ""
      }
    </div>
  `;
    ElMessage({
      type: colorMap[type],
      message: messageHTML,
      dangerouslyUseHTMLString: true,
      showClose: true,
      duration,
      customClass: "el-message-a",
    });
  };
  // 使用tableListQuery替代pages
  const pagerChange = (pager: { currentPage: number; pageSize: number }) => {
    tableListQuery.pageSize = pager.pageSize;
    tableListQuery.pageNo = pager.currentPage;
  };

  // 批量操作相关状态
  const showCLBatchOpToolbarGantt = ref(false);

  const handleShowRecords = (records: ProjectNode[]) => {
    console.log("handleShowRecords", records);
    selectedRecords.value = records;
    showCLBatchOpToolbar.value = records.length > 0;
    showCLBatchOpToolbarGantt.value = records.length > 0;
  };

  // 处理批量删除操作
  const handleBatchDelete = () => {
    if (selectedRecords.value.length === 0) return;

    // 调用删除节点的函数处理批量删除
    selectedRecords.value.forEach((record) => {
      handleDeleteNode(record);
    });

    // 删除完成后清空选中状态
    selectedRecords.value = [];
    showCLBatchOpToolbar.value = false;
    showCLBatchOpToolbarGantt.value = false;
  };
  const handleCreateOrEdit = async (formData: Record<string, any>) => {
    // console.log(formData, "handleCreateOrEdit");
    if (operate.value === "edit") {
      tableData.value.forEach((item, index) => {
        if (item.id === selectedNode.value.id) {
          tableData.value[index] = { ...item, ...formData };
        }
      });
      dialogVisible.value = false;
      selectedNode.value = {};
    }
  };
  /**
   * @description 文件上传成功
   */
  const UploadComplete = async (data: any) => {
    console.log(data, "data");
    const { successFiles } = data ?? {};
    try {
      const listFile = successFiles[0];
      let type = "";
      if (selectedProject.value.id === "0") type = "PROJECT_INPUT";
      else if (selectedProject.value.id === "9999") type = "PROJECT_OUTPUT";
      const params = [
        {
          createTime: formatDate(listFile.raw.lastModifiedDate, "datetime"),
          fileId: listFile.docId,
          fileName: listFile.name,
          source: "UPLOAD",
          type,
          projectId: currentProjectId,
          taskId: ["0", "9999"].includes(selectedProject.value.id)
            ? ""
            : selectedProject.value.id,
          filePath: listFile?.raw?.webkitRelativePath ?? "",
        },
      ];
      console.log("params", params, listFile);
      const res = await uploadFile(params);
      console.log("res", res);
      if (res) showFileMessage("success", "上传成功", [listFile.name]);
      else showFileMessage("error", "上传失败", [listFile.name]);
      onNodeSelected(selectedProject.value);
    } catch (error) {}
  };

  // 显示字段配置弹窗
  const showFieldConfigPopup = () => {};
  provide("showFieldConfigPopup", showFieldConfigPopup);
  onMounted(() => {
    fetchData();
  });
</script>

<style scoped lang="scss">
  .container {
    height: 100vh;
  }
  .table-wrapper {
    height: 100%;
  }
  .table-container {
    background-color: #fff;
    padding: 0 20px;
    margin-top: 20px;
    position: relative;
  }
  /* 滚动条样式 */
  .table-container::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }
  .table-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }
  .table-container::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;
  }
  .table-container::-webkit-scrollbar-thumb:hover {
    background: #555;
  }
  .toolbar-container-left {
    position: relative;
    top: 15px;
    left: 25px;
    height: 25px;
    display: flex;
    align-items: center;
    width: 50%;
  }
  .toolbar-container-left-text {
    font-size: 18px;
    font-weight: 500;
  }
  :deep(.toolbar-container) {
    right: 24px;
  }
  :deep(.el-button--primary) {
    background-color: #1aa1fb;
    border: 1px solid #1aa1fb;
    &:hover {
      background-color: rgba(26, 161, 251, 0.5);
      border: 1px solid rgba(26, 161, 251, 0.4);
    }
  }
  .button-text {
    font-size: 14px;
    font-weight: 500;
    margin-left: 4px;
  }
  .batch-btn {
    //padding: 4px 12px;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 14px;
    color: #42464e;
    height: 28px;
    width: 48px;
  }

  .batch-btn:hover {
    color: #42464e;
    background-color: rgba(31, 35, 41, 0.1);
  }
</style>
<style lang="scss">
  .el-message-a {
    box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.2);
  }
</style>
